import 'package:sonora/models/sj_medal_data.dart';
import 'package:sonora/utils/sj_storage_utils.dart';

class SjMedalUtils {
  static final SjMedalUtils _instance = SjMedalUtils._internal();

  // 私有的构造函数
  SjMedalUtils._internal() {
    _init();
  }

  // 公共的静态方法来获取该实例
  static SjMedalUtils get instance => _instance;

  void _init() async {
  }

  List<Map<String, dynamic>> _jsonMap() {
    final List<Map<String, dynamic>> list = [
      {
        'medalId': '1',
        'title': 'Harmony Voyager Badge',
        'dec': 'This medal is for you who love music',
        'assetPath': 'assets/images/xz_sm_1.png'
      },
      {
        'medalId': '2',
        'title': 'Resonance Explorer Badge',
        'dec': 'Go to publish an article to unlock this badge',
        'assetPath': 'assets/images/xz_sm_2.png'
      },
      {
        'medalId': '3',
        'title': 'Rhythmic Navigator Badge',
        'dec': 'Go to an article and post your comment',
        'assetPath': 'assets/images/xz_sm_3.png'
      },
    ];
    return list;
  }

  Future<List<SjMedalData>?> get medalList async {
    List<SjMedalData>? list = await SjStorageUtils.getMedalList();
    if (list == null) {
      list = _jsonMap().map((e) => SjMedalData.fromJson(e)).toList();
      SjStorageUtils.saveMedalList(list);
    }
    return list;
  }

  void saveMedalList(List<SjMedalData>? list) {
    if (list == null) return;
    SjStorageUtils.saveMedalList(list);
  }

  void updateMedalIsObtain(bool isObtain, int index) async {
    List<SjMedalData>? medalList = await instance.medalList;
    if (medalList != null && medalList.length > index) {
      SjMedalData medalData = medalList[index];
      SjMedalData result = medalData.copyWith(isObtain: isObtain);
      medalList.replaceRange(index, index + 1, [result]);
      instance.saveMedalList(medalList);
    }
  }
}
